package com.neusoft.crm.utils;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * 配置文件中密码加解密工具类，用于生成数据库连接密钥
 *
 * @author msprc
 */
public class JasypUtil {

    private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";

    /**
     * 获取加密器
     *
     * @param factor 加密秘钥
     * @return 加密器
     */
    private static PooledPBEStringEncryptor getEncryptor(String factor) {
        // 1. 创建加解密工具实例
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        // 2. 加解密配置
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(factor);
        config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
        // 为减少配置文件的书写，以下都是 Jasyp 3.x 版本，配置文件默认配置
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

    /**
     * Jasyp 加密（PBEWITHHMACSHA512ANDAES_256）
     *
     * @param plainText 待加密的原文
     * @param factor    加密秘钥
     * @return java.lang.String
     */
    public static String encryptWithSha512(String plainText, String factor) {
        PooledPBEStringEncryptor encryptor = getEncryptor(factor);
        return encryptor.encrypt(plainText);
    }

    /**
     * Jaspy解密（PBEWITHHMACSHA512ANDAES_256）
     *
     * @param encryptedText 待解密密文
     * @param factor        解密秘钥
     * @return java.lang.String
     */
    public static String decryptWithSha512(String encryptedText, String factor) {
        PooledPBEStringEncryptor encryptor = getEncryptor(factor);
        return encryptor.decrypt(encryptedText);
    }

    public static void main(String[] args) {
        // 加密密钥
        String factor = "neusoftCrm2023";
        // 要加密的字符串
        String plainText = "123";

        String encryptWithSha512Str = encryptWithSha512(plainText, factor);
        String decryptWithSha512Str = decryptWithSha512(encryptWithSha512Str, factor);
        Slf4j2Logger.LOGGER.info("要加密的字符串:" + plainText);
        Slf4j2Logger.LOGGER.info("加密密钥:" + factor);
        Slf4j2Logger.LOGGER.info("采用AES256加密后原文对应的密文:" + encryptWithSha512Str);
        Slf4j2Logger.LOGGER.info("采用AES256解密后密文对应的原文:" + decryptWithSha512Str);
    }
}